package frontend.counter;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.swing.JLabel;
import javax.swing.JPanel;


/**
 * the timer that run in a separator thread to count the time
 * 
 * @author zhang.yingchun
 *
 */
public class Timer extends JPanel{
	/**
	 * 
	 */
	private static final long serialVersionUID = -299176052566315348L;
	private JLabel dateLbl = new JLabel();	
	private JLabel timeLbl = new JLabel();
	
	private Thread timer = new Thread(new Runnable() {
	
		@Override
		public void run() {
			while (true) {
				Calendar cal = Calendar.getInstance();
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
				SimpleDateFormat timeFormat = new SimpleDateFormat("HH时mm分ss秒");
				Date date = cal.getTime();
				String dateStr = dateFormat.format(date);
				String timeStr = timeFormat.format(date);
				dateLbl.setText(dateStr);
				timeLbl.setText(timeStr);
				try {
					timer.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
		}
	}, "time counter");
	public Timer() {
		setSize(new Dimension(100,400));
		setBackground(Color.black);
		setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		c.gridx = 0;
		c.gridy = 0;
		add(dateLbl, c);
		c.gridy = 1;
		add(timeLbl, c);
		initLabel();
		timer.start();
	}
	
	private void initLabel() {
		Font font = new Font("Dialog", Font.BOLD, 28);
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
		SimpleDateFormat timeFormat = new SimpleDateFormat("HH时mm分ss秒");
		Date date = cal.getTime();
		String dateStr = dateFormat.format(date);
		String timeStr = timeFormat.format(date);
		dateLbl.setFont(font);
		timeLbl.setFont(font);
		dateLbl.setForeground(Color.green);
		timeLbl.setForeground(Color.green);
		dateLbl.setText(dateStr);
		timeLbl.setText(timeStr);
	}
}
